package com.swak.io.nio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

@SuppressWarnings("resource")
public class Bio {

	static class BioThread extends Thread {
		Socket client;

		public BioThread(Socket client) {
			this.client = client;
		}

		@Override
		public void run() {
			BufferedReader reader = null;
			try {
				InputStream in = client.getInputStream();
				reader = new BufferedReader(new InputStreamReader(in));
				while (true) {
					String dataline = reader.readLine(); // 阻塞2
					if (null != dataline) {
						System.out.println(dataline);
					} else {
						client.close();
						break;
					}
				}
				System.out.println("客户端断开");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException e) {
					}
				}
			}
		}
	}

	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(9090, 20);
		System.out.println("Server is start, listening in 9090");
		while (true) {
			Socket client = server.accept();
			System.out.println("client \t conneted. " + client.getPort());
			new BioThread(client).start();
		}
	}
}
